package cn.xuqiudong.blog.module.third.service.impl;

import cn.xuqiudong.blog.constant.GlobalFieldParams;
import cn.xuqiudong.blog.constant.ThirdProperties;
import cn.xuqiudong.blog.constant.ThirdUserType;
import cn.xuqiudong.blog.module.third.service.AbstractAuthService;
import cn.xuqiudong.common.base.craw.CrawlConnect;
import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.blog.model.BlogThirdUser;
import cn.xuqiudong.common.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @author Vic.xu
 * 说明 :  gitee 授权实现
 * @since  2020/7/21 0021 17:57
 */
@Service
public class GiteeAuthService extends AbstractAuthService {

    @Autowired
    private ThirdProperties thirdProperties;

    @Override
    public GlobalFieldParams.ThirdTypeEnum type() {
        return GlobalFieldParams.ThirdTypeEnum.gitee;
    }

    /**
     * 获取AccessToken   @link https://gitee.com/api/v5/oauth_doc#/list-item-2
     * @param code
     *
     * https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
     * @return
     */
    @Override
    public String getAccessToken(String code) {
        ThirdProperties.ThirdAuthConfig config = config();
        CrawlConnect crawlConnect = CrawlConnect.build(config.getAccessTokenUrl()).validateTlsCertificates();
        crawlConnect.data("client_secret", config.getClientSecret());
        crawlConnect.data("code", code);
        String token = "";
        try {
            /*
            text 的数据格式
            {
                "access_token":"b3448f7342fa2b80296c0c8c6563212d",
                "token_type":"bearer",
                "expires_in":86400,
                "refresh_token":"e913822cc399c66e20c241c780ba0be657b938a8db9e19f9b2dbce9751453f7a",
                "scope":"user_info emails",
                "created_at":1595398849
            }
             */
            String text = crawlConnect.postBodyText();
            logger.info("通过code[{}]获取授权码返回数据[{}]", code, text);
            return JsonUtil.jsonToObject(text, new TypeReference<Map<String, String>>() {
            }).get("access_token");
        } catch (IOException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new CommonException("获取授权码出了点问题");
        }
    }

    /**
     * 根据授权码获取用户信息
     * @param accessToken
     * @return
     */
    @Override
    public BlogThirdUser getUserInfo(String accessToken) {
        CrawlConnect crawlConnect = CrawlConnect.build(config().getUserUrl()).validateTlsCertificates();
        crawlConnect.data("access_token", accessToken);
        try {
             /*
            {
                id: 539873,
                login: "lcxm",
                name: "临窗旋墨",
                avatar_url: "https://portrait.gitee.com/uploads/avatars/user/179/539873_lcxm_1578927048.jpg",
                url: "https://gitee.com/api/v5/users/lcxm",
                html_url: "https://gitee.com/lcxm",
                followers_url: "https://gitee.com/api/v5/users/lcxm/followers",
                following_url: "https://gitee.com/api/v5/users/lcxm/following_url{/other_user}",
                gists_url: "https://gitee.com/api/v5/users/lcxm/gists{/gist_id}",
                starred_url: "https://gitee.com/api/v5/users/lcxm/starred{/owner}{/repo}",
                subscriptions_url: "https://gitee.com/api/v5/users/lcxm/subscriptions",
                organizations_url: "https://gitee.com/api/v5/users/lcxm/orgs",
                repos_url: "https://gitee.com/api/v5/users/lcxm/repos",
                events_url: "https://gitee.com/api/v5/users/lcxm/events{/privacy}",
                received_events_url: "https://gitee.com/api/v5/users/lcxm/received_events",
                type: "User",
                blog: "http://xuqiudong.cn/",
                weibo: null,
                bio: "曾经诗人，小小码农。",
                public_repos: 14,
                public_gists: 4,
                followers: 0,
                following: 1,
                stared: 3,
                watched: 33,
                created_at: "2015-10-20T10:39:40+08:00",
                updated_at: "2020-07-22T08:22:13+08:00",
                email: null
                }
             */
            String text = crawlConnect.getBodyText();
            Map<String, String> result = JsonUtil.jsonToObject(text, new TypeReference<Map<String, String>>() {
            });
            BlogThirdUser user = new BlogThirdUser();
            user.setAvatar(result.get("avatar_url"));
            user.setType(ThirdUserType.gitee.name());
            user.setIdentifier(result.get("login"));
            user.setNickname(result.get("name"));
            logger.info("accessToken[{}]获取用户信息返回数据[{}]", accessToken, text);
            return user;
        } catch (IOException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new CommonException("获取账户信息出了点问题");
        }
    }

}
